'use strict';
app.controller('authorizeCtrl',['$scope','$state','$stateParams','utilService','authorizeService','toaster', function($scope,$state,$stateParams,utilService,authorizeService,toaster){

    $scope.platform = 2;
    $scope.treeList=[];
    $scope.roleId=$stateParams.id;
    $scope.platform=$stateParams.platform;

    // 查询功能块
    $scope.query = function(){

        $scope.queryState=true;
        // query data.
        authorizeService.findByPlatformWithRole($scope).then(function(result){

            switch (result.status){
                case 200:
                    $scope.treeList = result.data.children;
                    $scope.queryState=false;
                    break;
                case 601:
                    $state.go('app.404');
                    break;
                default :
                    toaster.pop('error', "操作失败", "发生未知错误！请联系管理员");
                    break
            }

        });
    }

    $scope.query();

    //保存
    $scope.functionList=[];
    $scope.save=function(){
        $scope.functionList=[];
        for(var i=0;i<$scope.treeList.length;i++){
            if($scope.treeList[i].isSelect==1){
                var idx = $scope.functionList.indexOf($scope.treeList[i].id) ;
                if(idx==-1){
                    $scope.functionList.push($scope.treeList[i].id);
                }
            }
            itemFunc($scope.treeList[i]);
        }
        add();
    }

    var itemFunc=function(item){
        for(var i=0;i<item.children.length;i++){
            if(item.children[i].isSelect==1){
                var idx = $scope.functionList.indexOf(item.children[i].id) ;
                if(idx==-1){
                    $scope.functionList.push(item.children[i].id);
                }
                itemFunc(item.children[i]);
            }
        }
    }

    $scope.app.loading = false;

    function add(){
        if($scope.app.loading){
            return;
        }

        $scope.app.loading=true;

        authorizeService.add($scope).then(function(result){
            switch (result.status){
                case 200:
                    $scope.app.loading=false;
                    toaster.pop('success', "提示", "操作成功");
                    $state.go("app.role");
                    break;
                default:
                    $scope.app.loading=false;
                    toaster.pop('error', "操作失败", "发生未知错误！请联系管理员");
                    break
            }
        });
    }


}]);